package wicketforge.converter.dialog;

import java.awt.*;

import javax.swing.*;

import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import wicketforge.converter.BasePathConverter;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;

public abstract class BasePathConverterDialog<C extends BasePathConverter> extends DialogWrapper {

	private final C basePathConverter;

	private JTextField nameField;

	protected BasePathConverterDialog(@NotNull final Component parent, final C basePathConverter,
			final boolean canBeParent) {
		super(parent, canBeParent);
		this.basePathConverter = basePathConverter;
	}

	protected void createNameField(final JComponent parent) {
		Box nameBox = Box.createHorizontalBox();
		nameBox.add(new JLabel("Name:", SwingConstants.LEFT));
		nameBox.add(Box.createHorizontalStrut(5));
		nameField = new JTextField(basePathConverter.getName(), 10);
		nameBox.add(nameField);
		parent.add(nameBox);
	}

	@Nullable
	@Override
	public JComponent getPreferredFocusedComponent() {
		if (StringUtils.isEmpty(getName())) {
			return nameField;
		}
		return null;
	}

	@Override
	public boolean showAndGet() {
		boolean isOk = super.showAndGet();
		if (isOk) {
			basePathConverter.setName(getName());
		}
		return isOk;
	}

	protected C getPathConverter() {
		return basePathConverter;
	}

	private String getName() {
		return nameField.getText();
	}

	@Nullable
	@Override
	protected ValidationInfo doValidate() {

		if (StringUtils.isEmpty(nameField.getText())) {
			return new ValidationInfo("Converter must have a name.", nameField);
		}
		return null;
	}
}
